const RoleModel = require('../../db/models/role');
const MenuModel = require('../../db/models/menu');

// 查询列表（按条件查询）
const queryRoleList = async function (ctx, next) {
  let params = ctx.request.query;
  const reg = new RegExp(params.name, 'i');
  let roleList = await RoleModel.find({
    $or: [{ name: { $regex: reg } }]
  });
  ctx.body = roleList;
}

// 添加角色
const addRole = async function (ctx, next) {
  let data = ctx.request.body;
  let res = await RoleModel.find({ value: data.value });
  if (res.length) {
    ctx.body = {
      success: false,
      msg: '已存在该权限字符！',
      show: true
    }
    return;
  }
  await RoleModel.create(data);
  await MenuModel
    .updateMany(
      { key: { $in: data.menus } },
      { $push: { role: data.value } }
    )
    .then(() =>{
      ctx.body = {
        success: true
      }
    })
    .catch(err => {
      ctx.body = {
        success: false,
        msg: err.message
      }
    })
}

// 删除角色
const deleteRole = async function (ctx, next) {
  let params = ctx.request.query;
  await MenuModel
    .updateMany({ $pull: { role: { $in: params.roles.split(',') } } })
  await RoleModel
    .deleteMany({ _id: { $in: params._id.split(',') } })
    .then(() => {
      ctx.body = {
        success: true
      }
    })
    .catch(err => {
      ctx.body = {
        success: false,
        msg: err.message
      }
    })
}

// 更新角色
const updateRole = async function (ctx, next) {
  let data = ctx.request.body;
  let res = await RoleModel.find({ value: data.value });
  if (res.length && res[0].value !== data.value) {
    ctx.body = {
      success: false,
      msg: '已存在该权限字符！',
      show: true
    }
    return;
  }
  await RoleModel.where({ _id: data._id }).updateOne(data)
  let sql = null;
  if (data.state === 'add') {
    sql = { $push: { role: data.value } }
  } else {
    sql = { $pull: { role: data.value } }
  }
  await MenuModel
    .updateMany({ key: { $in: data.addMenu } }, sql)
    .then(() =>{
      ctx.body = {
        success: true
      }
    })
    .catch(err => {
      ctx.body = {
        success: false,
        msg: err.message
      }
    })
}

// 查询单个角色信息
const queryOneRole = async function (ctx, next) {
  let params = ctx.request.query;
  await RoleModel.find(params).then(res => {
    ctx.body = {
      success: true,
      data: res
    }
  }).catch(err => {
    ctx.body = {
      success: false,
      msg: err.message
    }
  })
}

module.exports = {
  queryRoleList,
  addRole,
  deleteRole,
  updateRole,
  queryOneRole
}